<?php

namespace McUser\Model;
use Common\Model\CommonModel;
load("@.myfunc");

/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

class TokenModel extends CommonModel {

	protected $trueTableName = 'bg_token';
	
	/**
	 * 得到IP地址.
	 */
	public function getip()
	{
	    if(!empty($_SERVER["HTTP_CLIENT_IP"]))
	    {
	        $cip = $_SERVER["HTTP_CLIENT_IP"];
	    }
	    else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
	    {
	        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	    }
	    else if(!empty($_SERVER["REMOTE_ADDR"]))
	    {
	        $cip = $_SERVER["REMOTE_ADDR"];
	    }
	    else
	    {
	        $cip = '';
	    }

	    preg_match("/[\d\.]{7,15}/", $cip, $cips);
	    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
	    unset($cips);
	    return $cip;
	}

	/*
	*	保存token
	*/
	public function save_token($mobile, $ip, $token){
		$where['mobile'] = $mobile;
		$info = $this -> where($where) -> select();
		$tokenOld = '';
		if(count($info) > 0)
			$tokenOld = $info[0]['token'];

		$user = D('McUser');
		$userID = $user -> get_userID_by_mobile($mobile);

		$data['userID'] = $userID;
		$data['mobile'] = $mobile;
		$data['ip'] = $ip;
		$data['token'] = $token;
		$data['tokenOld'] = $tokenOld;
		$data['create_time'] = date('Y-m-d H:i:s', time());
		
		$where['mobile'] = $mobile;
		$dd = $this -> where($where) -> select();
		if ($dd)
			$this -> where($where) -> save($data);		
		else
			$this -> add($data);		
	}

	/**
	 * [更新 userID 的 token]
	 * @param  [type] $userID [description]
	 * @return [type]         [description]
	 */
	public function update_token($userID){
		$user = D('McUser');
		$data = $user -> read_user_info($userID);

		$mobile = $data['mobile'];
		$token = $this -> create_token($mobile);
		$ip = $this -> getip();

		// 保存 token , 并返回.
		$this -> save_token($mobile, $ip, $token);
		return $token;
	}

	/*
	*	比对 token
	*/
	public function compare_token_by_mobile($mobile, $token){
		// $where['mobile']=$mobile;
	 	//    $where['token']=$token;
	    $where = 'mobile="' . $mobile . '" and (token="'.$token.'" or tokenOld="'.$token.'")';

	    $result = $this->where($where)->count();
	    if($result > 0){
	        return true;
	    }
	    else{
	    	return false;
	    }
	}

	/*
	*	比对 token 
	*/
	public function compare_token_by_userID($userID, $token){
		// $where['userID']=$userID;
	 	//    $where['token']=$token;
	    $where = 'userID=' . $userID . ' and (token="'.$token.'" or tokenOld="'.$token.'")';

	    $re['compareCode'] = false;
	    $re['overtime'] = false;

	    $result = $this->where($where)->select();

	    // echo $this -> getlastsql();
	    // 比较 token 的时间: 如果 token 相等, 有效期是24小时, 如果是 tokenOld 相等, 则是 10 分钟.
	    $expire = 10;
	    $isTokenOld = true;

	    if(count($result)>0){
	    	if($result[0]['token'] === $token){
	    		$expire = 1440;		// 60 * 24
	    		$isTokenOld = false;
	    	}
	    			
	    	// 检查 create_time ;
	    	$create_time = $result[0]['create_time'];

	    	$zero1=strtotime(date("Y-m-d H:i:s")); 	//当前时间
	    	$zero2=strtotime($create_time);  		

	    	$d=ceil(($zero1-$zero2)/60); 			//60s

	    	// echo '$d:' + $d;

	    	if($d>$expire){	    
	    		// tokenOld 超时, 直接算 token 错误, 同时把 tokenOld=''; 
	    		if($isTokenOld === true){
	    			$w['userID']=$userID;
	    			$w['tokenOld']=$token;
	    			$data['tokenOld'] = '';
	    			$this -> where($w) -> save($data);
	    			return $re;
	    		}else{
	    			// token 超时, 要更换新的 token.
	    			$re['overtime'] = true;
	    		}	    		
	    	}

	        $re['compareCode'] = true;
	    }

	    return $re;
	}

	/*
	*	生成 token	
	*/
	public function create_token($mobile){
		
		$token = sp_password($mobile.'-'.date("H:i:s",time()));
		return $token;
	    
	}

	/*
	*	注销, 删除 token
	*/
	public function delete_token($mobile){
		
		$where['mobile'] = $mobile;
		$this -> where($where) -> delete();
	    
	}


}